<template>
  <span>
    <!-- 有权限 -->
    <span v-if="hasPermission">
      <!-- 普通路由跳转 -->
      <router-link v-if="to && !params && !query" :to="{ name: to, params: { id } }" class="d-link">
        <slot>{{ title }}</slot>
      </router-link>
      <!-- 路由带 params -->
      <router-link v-else-if="to && params" :to="{ name: to, params }" class="d-link">
        <slot>{{ title }}</slot>
      </router-link>
      <!-- 路由带 query -->
      <router-link v-else-if="to && query" :to="{ name: to, query }" class="d-link">
        <slot>{{ title }}</slot>
      </router-link>
      <!-- 非路由跳转，触发 click 事件 -->
      <span v-else class="d-link" @click="linkClick">
        <slot>{{ title }}</slot>
      </span>
    </span>
    <!-- 无权限：仅展示文字 -->
    <span v-else>
      <slot>{{ title }}</slot>
    </span>
  </span>
</template>

<script setup lang="ts">
  defineOptions({ name: 'DetailLink' })
  import { computed } from 'vue'
  import { checkPermission } from '@/utils/permission'

  interface Props {
    title?: string
    id?: string
    to?: string
    params?: Record<string, any>
    query?: Record<string, any>
    permission?: string | null
  }

  const props = withDefaults(defineProps<Props>(), {
    title: '',
    id: '',
    to: '',
    permission: null,
  })

  const emit = defineEmits<{
    (e: 'click', id?: string): void
  }>()

  const hasPermission = computed(() => {
    return !props.permission || checkPermission([props.permission])
  })

  function linkClick() {
    console.log('Link clicked:', props.id)
    emit('click', props.id)
  }
</script>

<style scoped>
  .d-link {
    color: #409eff;
    cursor: pointer;
    text-decoration: none;
  }
</style>
